# coding=utf-8
from datetime import timedelta
from src.util.pathutil import SOURCE_DIR
from uuid import uuid4
import json

db_config_path = SOURCE_DIR.joinpath("config.json")


def read_config():
    """read json config file and convert to json obj"""
    content = None
    with open(db_config_path, "r", encoding="utf-8") as f:
        content = f.read()
    config_obj = json.loads(content)
    return config_obj


def get_server_config():
    """get flask server config"""
    config = read_config()
    # env = config.get("env")
    # server_config = config.get("server").get(env)
    server_config = config.get("server")
    return server_config


def get_db_config():
    """get database config"""
    config = read_config()
    # env = config.get("env")
    # db_config = config.get("db").get(env)
    db_config = config.get("db")
    return db_config


db_config_obj = get_db_config()
db_type = db_config_obj.get("db_type")
host = db_config_obj.get("host")
port = db_config_obj.get("port")
user = db_config_obj.get("username")
pwd = db_config_obj.get("password")
db_name = db_config_obj.get("dbname")
db_debug = db_config_obj.get("debug")


def get_db_uri():
    """get connect sqlalchemy orm uri"""
    # mysql+pymysql://your_username:your_password@localhost/your_database
    sql_alchemy_database_uri = ""
    if db_type == "mysql":
        sql_alchemy_database_uri = f"mysql+pymysql://{user}:{pwd}@{host}:{port}/{db_name}?charset=utf8&autocommit=true"
    if db_type == "oracle":
        sql_alchemy_database_uri = f"oracle+cx_oracle://{user}:{pwd}@//{host}:{port}/{db_name}"
    # print(sql_alchemy_database_uri)
    return sql_alchemy_database_uri


class DbConfig(object):
    """database config"""

    # database uri config
    SQLALCHEMY_DATABASE_URI = get_db_uri()
    # True will track and trigger signal effect orm performance but this attr when obj change can catch message
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    # when something change True will auto commit but effect orm performance
    SQLALCHEMY_COMMIT_ON_TEARDOWN = False
    # True orm show all sql message on stander output
    SQLALCHEMY_ECHO = False
    # database connect pool size default 5
    SQLALCHEMY_POOL_SIZE = 5
    # database connect pool timeout default 10
    SQLALCHEMY_POOL_TIMEOUT = 30
    # auto cg database connect object time
    SQLALCHEMY_POOL_RECYCLE = 120
    # auto commit transaction
    SQLALCHEMY_AUTOCOMMIT = True
    # secret key
    SECRET_KEY = str(uuid4())
    # session timeout default 7 days
    PERMANENT_SESSION_LIFETIME = timedelta(days=7)
